package cn.ffcs.uec.outStaffDataModificationApply.action;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffDataModificationApply.action.bean.OutStaffPartyLogApprovalViewMainBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.manager.ActRunTaskManager;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecPartyLogManager;
import cn.ffcs.uec.staff.model.UecPartyLog;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;

/**
 * 外包 政治面貌审批弹窗
 * 
 * @author liuxiaodong
 *
 */
@Controller
@Scope("prototype")
public class OutStaffPartyLogApprovalViewMainComposer extends
		BasePortletComposer {

	private static final long serialVersionUID = 8556355871911063693L;

	private OutStaffPartyLogApprovalViewMainBean bean = new OutStaffPartyLogApprovalViewMainBean();

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	private UecPartyLogManager uecPartyLogManager = (UecPartyLogManager) ApplicationContextUtil
			.getBean("uecPartyLogManager");

	private ActRunTaskManager actRunTaskManager = (ActRunTaskManager) ApplicationContextUtil
			.getBean("actRunTaskManager");

	/**
	 * 外包人员基本信息
	 */
	private UecOutStaffInfo outStaffInfo = UecOutStaffInfo.newInstance();

	private UecPartyLog uecPartyLog = UecPartyLog.newInstance();

	private String taskDefKey;

	private String opType;

	private String procDefKey;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);

	}

	/**
	 * 界面初始化
	 */
	public void onCreate$outStaffPartyLogApprovalViewMainWin() {
		bandListbox();
		bindBean();
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {
		// 非查看历史工单
		if (!ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 添加校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	public void postApprovalData() throws InterruptedException {
		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}

		PubUtil.fillPoFromEditorBean(uecPartyLog, bean);
		uecPartyLog
				.setGlbdef1(DateUtil.dateToStr(bean.getGlbdef1().getValue()));
		uecPartyLog.setPartyDate(DateUtil.dateToStr(bean.getPartyDate()
				.getValue()));
		uecPartyLog
				.setGlbdef2(DateUtil.dateToStr(bean.getGlbdef2().getValue()));
		uecPartyLog.setPartyDueDate(DateUtil.dateToStr(bean.getPartyDueDate()
				.getValue()));
		uecPartyLog.setBeginDate(DateUtil.dateToStr(bean.getBeginDate()
				.getValue()));
		uecPartyLog
				.setEndDate(DateUtil.dateToStr(bean.getEndDate().getValue()));
		uecPartyLog.setModifiedtime(DateUtil.getCurrenDate());
		uecPartyLog.setModifier(currentName);
		DefaultDaoFactory.getDefaultDao().updateObject(uecPartyLog);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);
	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});
	}

	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭弹窗
	 */
	public void onCancel() {
		this.bean.getOutStaffPartyLogApprovalViewMainWin().onClose();
	}

	/**
	 * 获取传值
	 * 
	 * @throws ParseException
	 * @throws WrongValueException
	 */
	private void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getOutStaffPartyLogApprovalViewMainWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 1.获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		opType = (String) arg.get("opType");
		if ("onView".equals(opType)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {

			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		opType = (String) arg.get("opType");
		procDefKey = (String) arg.get("procDefKey");
		if (null != oaBaseObject) {
			List<Map<String, Object>> list = actRunTaskManager
					.getRuTasks(oaBaseObject.getProcInstId());
			if (null == list) {
				ZkUtil.showError("未知错误!", "错误信息");
				return;
			}
			if (list.size() == 0) {
				if (ApprovalUtil.OUT_STAFF_PARTYLOG_EDIT.equals(procDefKey)) {
					String partyLogIdTmp = oaBaseObject.getPartyLogId();
					oaBaseObject.setPartyLogId(oaBaseObject.getPartyLogIdHis());
					oaBaseObject.setPartyLogIdHis(partyLogIdTmp);
				}
			}

			// 2.获取人员信息
			String outStaffId = oaBaseObject.getOutStaffId();
			outStaffInfo.setOutStaffId(Long.parseLong(outStaffId));
			outStaffInfo = uecOutStaffManager
					.findUecOutStaffInfoByOutStaffId(outStaffInfo);
			if (null != outStaffInfo) {
				PubUtil.fillBeanFromPo(outStaffInfo, bean);
				UecOrgOrgs newOrgOrgs = UecOrgOrgs.newInstance();
				newOrgOrgs.setPkOrg(outStaffInfo.getPkHrorg());
				newOrgOrgs = uecOrgOrgsManager
						.findUecOrgOrgsByUecOrgOrgs(newOrgOrgs);
				if (null != newOrgOrgs) {
					bean.getOrgName().setValue(newOrgOrgs.getName());
				}
			}
			// 政治面貌分新增和修改，如果是修改流程有对比信息，如果是新增流程无对比信息
			// 获取原数据
			if (ApprovalUtil.OUT_STAFF_PARTYLOG_EDIT.equals(procDefKey)) {
				String partyLogIdHis = oaBaseObject.getPartyLogIdHis();
				uecPartyLog = new UecPartyLog();
				uecPartyLog.setPartylogId(Long.valueOf(partyLogIdHis));
				uecPartyLog = uecPartyLogManager
						.findUecPartyLogById(uecPartyLog);
				// 政治面貌及党籍情况
				bean.getPartyNameHis().setValue(uecPartyLog.getPartyNameName());
				bean.getGlbdef1His().setValue(uecPartyLog.getGlbdef1());
				bean.getPartyUnitHis().setValue(uecPartyLog.getPartyUnit());
				bean.getPartyDateHis().setValue(uecPartyLog.getPartyDate());
				bean.getGlbdef2His().setValue(uecPartyLog.getGlbdef2());
				bean.getPartyDueDateHis().setValue(
						uecPartyLog.getPartyDueDate());
				bean.getPartyPsnHis().setValue(uecPartyLog.getPartyPsn());
				bean.getBeginDateHis().setValue(uecPartyLog.getBeginDate());
				bean.getEndDateHis().setValue(uecPartyLog.getEndDate());
				bean.getGlbdef3His().setValue(uecPartyLog.getGlbdef3());

			}
			if (ApprovalUtil.OUT_STAFF_PARTYLOG_ADD.equals(procDefKey)) {
				bean.getGroupboxHis().setVisible(false);
			}

			// 获取审批中人员政治面貌信息
			String partyLogId = oaBaseObject.getPartyLogId();
			uecPartyLog = UecPartyLog.newInstance();
			uecPartyLog.setPartylogId(Long.valueOf(partyLogId));
			uecPartyLog = uecPartyLogManager.findUecPartyLogById(uecPartyLog);
			if (null != uecPartyLog) {
				PubUtil.fillBeanFromPo(uecPartyLog, bean);
				bean.getGlbdef1().setValue(
						DateUtil.patternStrToDate(uecPartyLog.getGlbdef1()));
				bean.getPartyDate().setValue(
						DateUtil.patternStrToDate(uecPartyLog.getPartyDate()));
				bean.getGlbdef2().setValue(
						DateUtil.patternStrToDate(uecPartyLog.getGlbdef2()));
				bean.getPartyDueDate()
						.setValue(
								DateUtil.patternStrToDate(uecPartyLog
										.getPartyDueDate()));
				bean.getBeginDate().setValue(
						DateUtil.patternStrToDate(uecPartyLog.getBeginDate()));
				bean.getEndDate().setValue(
						DateUtil.patternStrToDate(uecPartyLog.getEndDate()));
			}
		}

	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canReject
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	private void bandListbox() {
		// 政治面貌及党籍情况 partyName
		ListboxUtils.rendererForEdit(bean.getPartyName(),
				NodeVoUtil.getDictionaries(UecConstants.POLITICAL_OUTLOOK));
	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getPartyName().getSelectedItem()
				.getValue())) {
			return "请填写政治面貌及党籍情况";
		}
		return null;
	}

}
